import { login,logout,changePass} from '@/api/user';
import { encryption } from '@/utils/utils';
import {getSession,setSession} from '../../api/storage';
import Router from '@/router/index';
import {Message} from "element-ui";

const state = {
  userinfo: getSession('userinfo') ||  '', //用户信息（用户名、头像、租户id、租户名、租户logo、微信绑定状态）
  token:"",
  projects:""
};
const mutations = {
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo;
    setSession('userinfo',userinfo)
  },
  SET_Token: (state, token) => {
    state.token = token;
  },
  SET_PROJECT: (state, projects) => {
    state.projects = projects;
  },
};
const actions = {
  // 用户登录
  login({commit},userInfo) {
    const user = encryption({
      data: userInfo,
      key: 'pigxpigxpigxpigx',
      param: ['password']
    })
    return new Promise((resolve, reject) => {
      login({'username': user.username, 'password': user.password}).then(res => {
        if(res.code == 0){
          commit('SET_USERINFO', res.data);
          resolve(res)
        }else{
          Message.error(res.msg)
          reject()
        }
      }).catch((error)=>{
        reject(error);
      })
    })
  },
  //修改密码
  changePass({commit},data){
    return new Promise((resolve, reject) => {
      changePass(data).then(res => {
        resolve(res)
      }).catch((error)=>{reject(error);})
    })
  },
  //退出
  logout({commit}){
    return new Promise((resolve, reject) => {
      logout().then(res => {
        commit('SET_Token', null);
        resolve(res);
      }).catch((error)=>{reject(error);})
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};